﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Business;
using AMM.Business.Project;
using AMM.CustomClassLibrary;
using AMM.CustomWinComponents.Validator;
using AMM.Model;
using AMM.Model.Business;
using AMM.Model.Project;

namespace AMM.UserControls {
    public partial class CustomerOrderEditControl : BaseEditControl {

        private FlexBindingSource<CustomerOrder> _fbs;

        public override object BaseEditModel {
            get {
                this._fbs.CurrentItem.CustomerOrderDetails = this.dgvProductEdit.GetDataSourceEx<CustomerOrderDetail>();
                return this._fbs.CurrentItem;
            }
            set {
                if (this._fbs == null) { this._fbs = new FlexBindingSource<CustomerOrder>(); }
                this._fbs.CurrentItem = (CustomerOrder)value;
            }
        }

        public CustomerOrderEditControl() {
            this.InitializeComponent();
        }

        private void BindProduct() {
            List<ProductViewModel> productList = new List<ProductViewModel>();
            ProductSearchModel searchModel = new ProductSearchModel() { IsEnabled = true };
            ProductProcessor productProcessor = new ProductProcessor();
            productList = productProcessor.FetchProductViewModelList(searchModel);
            this.Product.DisplayMemberEx = "Code";
            this.Product.ValueMemberEx = "Key";
            this.Product.HeightEx = 300;
            this.Product.WidthEx = 400;
            this.Product.PageSizeEx = this.PageSize;
            this.Product.DataBind(new ProductViewModel(), x => new { x.ProductType, x.Code, x.Name, x.Remarks }, productList);
        }

        private void BindCustomer() {
            CustomerSearchModel searchModel = new CustomerSearchModel() { IsEnabled = true };
            CustomerProcessor customerProcessor = new CustomerProcessor();
            List<CustomerViewModel> customerList = new List<CustomerViewModel>();
            customerList = customerProcessor.FetchCustomerViewModelList(searchModel);
            this.ddlCustomer.DisplayMemberEx = "Code";
            this.ddlCustomer.ValueMemberEx = "Key";
            this.ddlCustomer.HeightEx = 300;
            this.ddlCustomer.WidthEx = 400;
            this.ddlCustomer.PageSizeEx = this.PageSize;
            this.ddlCustomer.DataBind(new CustomerViewModel(), x => new { x.Code, x.Name, x.Linkman1 }, customerList);
        }

        private void CreateFormBindings() {
            this._fbs.CreateBinding(this.ddlCustomer, x => x.SelectedValueEx, y => y.CustomerId);
            this._fbs.CreateBinding(this.tbOrderNo, x => x.Text, y => y.OrderNo);
            this._fbs.CreateBinding(this.dtpOrderDate, x => x.Value, y => y.OrderDate);
            this._fbs.CreateBinding(this.dtpDeliverDate, x => x.Value, y => y.DeliverDate);
            this._fbs.CreateBinding(this.cmbCurrency, x => x.SelectedValue, y => y.CurrencyId);
            this._fbs.CreateBinding(this.cmbPaymentType, x => x.SelectedValue, y => y.PaymentTypeId);
            this._fbs.CreateBinding(this.cmbOrderType, x => x.SelectedValue, y => y.OrderTypeId);
            this._fbs.CreateBinding(this.tbRemarks, x => x.Text, y => y.Remarks);
            this._fbs.CreateBinding(this.attachment, x => x.Text, y => y.AttachmentId);
            this._fbs.CreateBinding(this.tbExchangeRate, x => x.Text, y => y.ExchangeRate, z => z.ToString("G0"), DataSourceUpdateMode.OnPropertyChanged);
            this._fbs.CreateBinding(this.tbTotalMoney, x => x.Text, y => y.TotalMoney, z => z.ToString("G0"), DataSourceUpdateMode.OnPropertyChanged);
            this._fbs.CreateBinding(this.tbTotalMoneyInLocal, x => x.Text, y => y.TotalMoneyInLocal, z => z.ToString("G0"), DataSourceUpdateMode.OnPropertyChanged);
            this._fbs.CreateBinding(this.tbTotalQuantities, x => x.Text, y => y.TotalQuantities, z => z.ToString("G0"), DataSourceUpdateMode.OnPropertyChanged);
        }

        private void BindValidation() {
            this.ValidatorForEdit.SetType(this.tbOrderNo, ValidationType.Required | ValidationType.RegularExpression);
            this.ValidatorForEdit.SetRequiredMessage(this.tbOrderNo, this.RequiredMessage);
            this.ValidatorForEdit.SetRegularExpression(this.tbOrderNo, "^[A-Za-z0-9-]+$");
            this.ValidatorForEdit.SetRegularExpressionMessage(this.tbOrderNo, "编码只能由字母，数字，连接线组成");

            this.ValidatorForEdit.SetType(this.ddlCustomer, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.ddlCustomer, this.RequiredMessage);

            this.ValidatorForEdit.SetType(this.cmbCurrency, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.cmbCurrency, this.RequiredMessage);

            this.ValidatorForEdit.SetType(this.cmbPaymentType, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.cmbPaymentType, this.RequiredMessage);

            this.ValidatorForEdit.SetType(this.dtpOrderDate, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.dtpOrderDate, this.RequiredMessage);

            this.ValidatorForEdit.SetType(this.dtpDeliverDate, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.dtpDeliverDate, this.RequiredMessage);

            this.ValidatorForEdit.SetType(this.tbExchangeRate, ValidationType.Required | ValidationType.RegularExpression);
            this.ValidatorForEdit.SetRequiredMessage(this.tbExchangeRate, this.RequiredMessage);
            this.ValidatorForEdit.SetRegularExpression(this.tbExchangeRate, "^([0-9]+.)?[0-9]+$");
            this.ValidatorForEdit.SetRegularExpressionMessage(this.tbExchangeRate, "汇率只能由数字组成");
        }

        private void Calculation() {
            int totalQuantities = 0;
            decimal totalMoeny = 0m, exchangeRate = 1m;
            decimal.TryParse(this.tbExchangeRate.Text, out exchangeRate);
            this.dgvProductEdit.GetDataSourceEx<CustomerOrderDetail>().ForEach(x => {
                totalQuantities += x.Quantity;
                totalMoeny += x.TotalMoney.HasValue ? x.TotalMoney.Value : 0m;
            });
            this.tbTotalQuantities.Text = totalQuantities.ToString("G0");
            this.tbTotalMoney.Text = totalMoeny.ToString("G0");
            this.tbTotalMoneyInLocal.Text = (totalMoeny * exchangeRate).ToString("G0");
        }

        private void CustomerEditControl_Load(object sender, EventArgs e) {
            if (this._fbs == null) { this._fbs = new FlexBindingSource<CustomerOrder>(); }
            this.dgvProductEdit.DataSourceEx = this._fbs.CurrentItem.CustomerOrderDetails.ToList();
            this.BindBasics(this.cmbCurrency, BasicsType.Currency);
            this.BindBasics(this.cmbPaymentType, BasicsType.PaymentType);
            this.BindBasics(this.cmbOrderType, BasicsType.OrderType);
            this.BindProduct();
            this.BindCustomer();
            this.CreateFormBindings();
            this.BindValidation();

            this.tbExchangeRate.KeyUp += new KeyEventHandler((s1, e1) => { this.Calculation(); });
        }

        private void dgvProductEdit_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
            if (e.RowIndex < 0) { return; }
            DataGridViewColumn currentColumn = this.dgvProductEdit.Columns[e.ColumnIndex];
            DataGridViewRow currentRow = this.dgvProductEdit.Rows[e.RowIndex];
            if (currentColumn.Name == "Price" || currentColumn.Name == "Quantity") {
                currentRow.Cells["TotalMoney"].Value =
                    (decimal)(currentRow.Cells["Price"].Value) * (int)(currentRow.Cells["Quantity"].Value);
                this.Calculation();
            }
        }
    }
}
